<?php
namespace api\modules\v1\models;

use Yii;
use yii\base\Model;
use common\models\User;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $mobile;
    public $password;
    public $vcode;
    public $verify_code;
    public $timestamp;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mobile', 'vcode', 'verify_code', 'password', 'timestamp'], 'filter', 'filter' => 'trim'],
            [['mobile', 'vcode', 'verify_code', 'password', 'timestamp'], 'required'],
            
            [['mobile', 'vcode', 'timestamp'], 'number'],            
            ['mobile', 'string', 'length' => [11, 11]],
            ['vcode', 'string', 'max' => 6],
            ['timestamp', 'string', 'max' => 10],
            ['verify_code', 'string', 'max' => 32],
            ['password', 'string', 'length' => [6, 24]],
        ];
    }
    
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'mobile' => Yii::t('app', '手机号'),
            'vcode' => Yii::t('app', '验证码'),
            'verify_code' => Yii::t('app', '加密验证码'),
            'timestamp' => Yii::t('app', '时间戳'),
            'password' => Yii::t('app', '会员密码'),
        ];
    }

    /**
     * @inheritdoc
     */
    public function signup()
    {
        if ($this->validate()) {
            // 校验验证码
            // 4dcb61931cd9d4b17acf3d153e3624f4 18638923187 1432647819 268864
            $verify_code = md5($this->mobile . $this->vcode . $this->timestamp);
            if ($verify_code != $this->verify_code) {
                //$this->addError('vcode', '验证码错误');
                //return $this;
            }
            $user = new User();
            $user->username = $this->mobile . '_' . mt_rand(1000, 9999);
            if ($user->findByMobile($this->mobile)) {
                $this->addError('mobile', '该手机号已被使用，请更换其它手机号');
                return $this;
            }
            $user->mobile = $this->mobile;
//             $user->mobile_bind = 1;
            $user->email = $this->mobile.'@yj.mangxiaoquan.com';
//             $user->email_bind = 0;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            $user->created_at = strval(time());
            $user->updated_at = strval(time());
            if ($user->save()) {
                $token = new LoginForm();
                return $token->createToken($user->id, $user->username, 'android');
            } else {
                return $user;
            }
        } else {
            return $this;
        }
    }
}
